<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    
    <title>第三章：使用QueryDSL与SpringDataJPA完成Update&amp;Delete | 恒宇少年De成长之路</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="我们上一章讲解了有关QueryDsl整合SpringDataJPA完成简单的单表条件查询，采用了两种模式进行查询一种是完全QueryDsl而另外一种则是整合的形式，既然单表的查询已经讲解接下来我们来看看QueryDsl与SpringDataJPA整合后的Update&amp;amp;Delete的多种处理模式。">
<meta name="keywords" content="SpringBoot,QueryDSL">
<meta property="og:type" content="article">
<meta property="og:title" content="第三章：使用QueryDSL与SpringDataJPA完成Update&amp;Delete">
<meta property="og:url" content="http://blog.yuqiyu.com/querydsl-chapter-3/index.html">
<meta property="og:site_name" content="恒宇少年De成长之路">
<meta property="og:description" content="我们上一章讲解了有关QueryDsl整合SpringDataJPA完成简单的单表条件查询，采用了两种模式进行查询一种是完全QueryDsl而另外一种则是整合的形式，既然单表的查询已经讲解接下来我们来看看QueryDsl与SpringDataJPA整合后的Update&amp;amp;Delete的多种处理模式。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-e948ae2a916d144c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-7590b995f33a3d79.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-3ed6067bca583a49.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-08ec7d76c93dac33.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-f1d4cb64234b160a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-01-23T16:09:54.415Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="第三章：使用QueryDSL与SpringDataJPA完成Update&amp;Delete">
<meta name="twitter:description" content="我们上一章讲解了有关QueryDsl整合SpringDataJPA完成简单的单表条件查询，采用了两种模式进行查询一种是完全QueryDsl而另外一种则是整合的形式，既然单表的查询已经讲解接下来我们来看看QueryDsl与SpringDataJPA整合后的Update&amp;amp;Delete的多种处理模式。">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/4461954-e948ae2a916d144c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
    

    
        <link rel="alternate" href="/" title="恒宇少年De成长之路" type="application/atom+xml" />
    

    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">恒宇少年De成长之路</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">首页</a>
                
                    <a class="main-nav-link" href="/archives">时间轴</a>
                
                    <a class="main-nav-link" href="/categories">文章专题</a>
                
                    <a class="main-nav-link" href="/tags">标签云</a>
                
                    <a class="main-nav-link" href="/about">关于我</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/css/images/avatar.png" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <!--button type="submit" class="search-form-submit"></button-->
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td ><a  class="main-nav-link" href="/.">首页</a></td>
                
                    <td ><a  class="main-nav-link" href="/archives">时间轴</a></td>
                
                    <td ><a  class="main-nav-link" href="/categories">文章专题</a></td>
                
                    <td ><a  class="main-nav-link" href="/tags">标签云</a></td>
                
                    <td ><a  class="main-nav-link" href="/about">关于我</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/css/images/avatar.png" />
            <h2 id="name">恒宇少年</h2>
            <h3 id="title">Java软件工程师 &amp; 程序猿</h3>
            <span id="location"><i class="fa fa-map-marker"></i>山东, 济南</span>
            <a id="follow" target="_blank" href="https://www.jianshu.com/u/092df3f77bca">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                43
                <span>文章</span>
            </div>
            <div class="article-info-block">
                2
                <span>标签</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/ppoffice/hexo-theme-icarus" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="twitter" class=tooltip>
                            <i class="fa fa-twitter"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="facebook" class=tooltip>
                            <i class="fa fa-facebook"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="dribbble" class=tooltip>
                            <i class="fa fa-dribbble"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="post-querydsl-chapter-3" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            第三章：使用QueryDSL与SpringDataJPA完成Update&amp;Delete
        </h1>
    

                
                    <div class="article-meta">
                        
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/querydsl-chapter-3/">
            <time datetime="2017-07-04T16:00:00.000Z" itemprop="datePublished">2017-07-05</time>
        </a>
    </div>


                        
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/QueryDSL-核心技术/">QueryDSL 核心技术</a>
    </div>

                        
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/QueryDSL/">QueryDSL</a>, <a class="tag-link" href="/tags/SpringBoot/">SpringBoot</a>
    </div>

                    </div>
                
            </header>
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>我们上一章讲解了有关QueryDsl整合SpringDataJPA完成简单的单表条件查询，采用了两种模式进行查询一种是完全QueryDsl而另外一种则是整合的形式，既然单表的查询已经讲解接下来我们来看看QueryDsl与SpringDataJPA整合后的Update&amp;Delete的多种处理模式。<br><a id="more"></a></p>
<h1 id="本章目标"><a href="#本章目标" class="headerlink" title="本章目标"></a>本章目标</h1><p>基于SpringBoot框架平台完成QueryDsl整合SpringDataJPA单表Update&amp;Delete操作。</p>
<h1 id="构建项目"><a href="#构建项目" class="headerlink" title="构建项目"></a>构建项目</h1><p>我们使用idea工具创建一个空的SpringBoot项目，把上一章<a href="http://www.jianshu.com/p/4e9d8adaeeb2" target="_blank" rel="noopener">第二章：使用QueryDSL与SpringDataJPA实现单表普通条件查询</a>内的配置文件复制到本章项目中（复制内容包含：application.yml，pom.xml内依赖，Bean，BaseJPA，UserJPA）复制完成后使用maven compile命令完成QueryDsl查询实体的自动创建，先来完成用户信息的更新，下面我们直接进入正题。</p>
<h1 id="更新实体信息"><a href="#更新实体信息" class="headerlink" title="更新实体信息"></a>更新实体信息</h1><p>我们采用两种方式进行更新实体信息，一种是完全采用SpringDataJPA的save方法，另外一种则是QueryDsl的update方法，下来我们先来看看SpringDataJPA如何完成更新实体信息。</p>
<h3 id="使用SpringDataJPA更新实体"><a href="#使用SpringDataJPA更新实体" class="headerlink" title="使用SpringDataJPA更新实体"></a>使用SpringDataJPA更新实体</h3><p>SpringDataJPA内置了一个save方法用于保存、更新实体内容，如果存在主键值则更新对应主键的row信息，反则是添加一条新信息，这一点跟Hibernate的saveOrUpdate方法比较相似。我们先来创建一个UserController控制器，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.querydsl.sample.chapter3.controller;</span><br><span class="line"></span><br><span class="line">import com.querydsl.jpa.impl.JPAQueryFactory;</span><br><span class="line">import com.yuqiyu.querydsl.sample.chapter3.bean.QUserBean;</span><br><span class="line">import com.yuqiyu.querydsl.sample.chapter3.bean.UserBean;</span><br><span class="line">import com.yuqiyu.querydsl.sample.chapter3.jpa.UserJPA;</span><br><span class="line">import org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line">import org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line">import org.springframework.web.bind.annotation.RestController;</span><br><span class="line"></span><br><span class="line">import javax.annotation.PostConstruct;</span><br><span class="line">import javax.persistence.EntityManager;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/7/4</span><br><span class="line"> * Time：22:15</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@RestController</span><br><span class="line">public class UserController</span><br><span class="line">&#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private UserJPA userJPA;</span><br><span class="line"></span><br><span class="line">    //实体管理者</span><br><span class="line">    @Autowired</span><br><span class="line">    private EntityManager entityManager;</span><br><span class="line"></span><br><span class="line">    //JPA查询工厂</span><br><span class="line">    private JPAQueryFactory queryFactory;</span><br><span class="line"></span><br><span class="line">    @PostConstruct</span><br><span class="line">    public void initFactory()</span><br><span class="line">    &#123;</span><br><span class="line">        queryFactory = new JPAQueryFactory(entityManager);</span><br><span class="line">        System.out.println(&quot;init JPAQueryFactory successfully&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面这个控制器与第二章内的控制器基本内容没有什么差别，在bean构造函数初始化时通过EntityManager对象实例化JPAQueryFactory查询工厂实体，方便我们接下来的查询操作，QueryDsl形式是需要建立在JPAQueryFactory对象基础上构建的。SpringDataJPA方式更新实体代码如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 使用Jpa更新会员信息</span><br><span class="line"> * @param userBean</span><br><span class="line"> */</span><br><span class="line">@RequestMapping(value = &quot;/updateWithJpa&quot;)</span><br><span class="line">public String updateWithJpa(UserBean userBean)</span><br><span class="line">&#123;</span><br><span class="line">    //保存会员信息相当于Hibernate内的SaveOrUpdate</span><br><span class="line">    userJPA.save(userBean);</span><br><span class="line">    return &quot;SUCCESS&quot;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>很简单并没有什么有难理解的地方，参数是通过界面Request方式传递的，下面我们运行下项目在上一章数据基础上尝试下更新操作。运行项目控制台输出下图1所示：<br><img src="http://upload-images.jianshu.io/upload_images/4461954-e948ae2a916d144c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1"><br>看到上图1中红色标出部分我们就可以通过浏览器进行访问路径尝试更新实体信息了，下面我们来访问下地址：<a href="127.0.0.1:8080/updateWithJpa?id=6&amp;name=change&amp;age=23&amp;address=SdJN&amp;pwd=123456" target="_blank" rel="noopener">127.0.0.1:8080/updateWithJpa?id=6&amp;name=change&amp;age=23&amp;address=SdJN&amp;pwd=123456</a>，界面输出内容如下图2所示：<br><img src="http://upload-images.jianshu.io/upload_images/4461954-7590b995f33a3d79.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2"><br>我们来看下控制台输出的日志内容，如下代码所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">Hibernate: </span><br><span class="line">    select</span><br><span class="line">        userbean0_.t_id as t_id1_0_0_,</span><br><span class="line">        userbean0_.t_address as t_addres2_0_0_,</span><br><span class="line">        userbean0_.t_age as t_age3_0_0_,</span><br><span class="line">        userbean0_.t_name as t_name4_0_0_,</span><br><span class="line">        userbean0_.t_pwd as t_pwd5_0_0_ </span><br><span class="line">    from</span><br><span class="line">        t_user userbean0_ </span><br><span class="line">    where</span><br><span class="line">        userbean0_.t_id=?</span><br><span class="line">Hibernate: </span><br><span class="line">    update</span><br><span class="line">        t_user </span><br><span class="line">    set</span><br><span class="line">        t_address=?,</span><br><span class="line">        t_age=?,</span><br><span class="line">        t_name=?,</span><br><span class="line">        t_pwd=? </span><br><span class="line">    where</span><br><span class="line">        t_id=?</span><br></pre></td></tr></table></figure></p>
<p>可以看到SpringDataJPA先去数据库查询了一边当前对象，比对发现与数据库内不一致并且存在主键值则执行了下面的Update语句，这里如果查询到的字段对应更新的内容一致时则不会执行下面的Update语句，我们再来访问下刚才的地址查看控制台输出如下代码块所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Hibernate: </span><br><span class="line">    select</span><br><span class="line">        userbean0_.t_id as t_id1_0_0_,</span><br><span class="line">        userbean0_.t_address as t_addres2_0_0_,</span><br><span class="line">        userbean0_.t_age as t_age3_0_0_,</span><br><span class="line">        userbean0_.t_name as t_name4_0_0_,</span><br><span class="line">        userbean0_.t_pwd as t_pwd5_0_0_ </span><br><span class="line">    from</span><br><span class="line">        t_user userbean0_ </span><br><span class="line">    where</span><br><span class="line">        userbean0_.t_id=?</span><br></pre></td></tr></table></figure></p>
<p>可以看到仅仅执行了查询并没有发起更新操作。</p>
<h3 id="使用QueryDsl更新实体"><a href="#使用QueryDsl更新实体" class="headerlink" title="使用QueryDsl更新实体"></a>使用QueryDsl更新实体</h3><p>下面我们来完全使用QueryDsl来更新实体，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">     * 使用QueryDsl更新会员信息</span><br><span class="line">     * @param userBean</span><br><span class="line">     */</span><br><span class="line">    @RequestMapping(value = &quot;/updateWithQueryDsl&quot;)</span><br><span class="line">    public String updateWithQueryDsl(UserBean userBean)</span><br><span class="line">    &#123;</span><br><span class="line">        //querydsl查询实体</span><br><span class="line">        QUserBean _Q_user = QUserBean.userBean;</span><br><span class="line"></span><br><span class="line">        queryFactory</span><br><span class="line">                .update(_Q_user)//更新对象</span><br><span class="line">                //更新字段列表</span><br><span class="line">                .set(_Q_user.name,userBean.getName())</span><br><span class="line">                .set(_Q_user.address,userBean.getAddress())</span><br><span class="line">                .set(_Q_user.age,userBean.getAge())</span><br><span class="line">                .set(_Q_user.pwd,userBean.getPwd())</span><br><span class="line">                //更新条件</span><br><span class="line">                .where(_Q_user.id.eq(userBean.getId()))</span><br><span class="line">                //执行更新</span><br><span class="line">                .execute();</span><br><span class="line">        return &quot;SUCCESS&quot;;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>我们第一步先获取了QUserBean查询对象，并且通过JPAQueryFactory对象构建了update方法处理，而update的参数就是需要更新的查询实体，当然update方法内仅支持更新单个查询实体。</p>
<p>接下来我们就设置要更新的字段内容了，这里就是我们随心所欲控制了。需要更新哪些字段就设置对应字段更新的内容即可。</p>
<p>设置完成更新字段后需要设置更新的条件，不设置也是可以的，当然这里肯定跟原生SQL一样，不设置条件就更新表内全部的数据。</p>
<p>最后一步至关重要，如果不调用execute方法就不会执行更新操作。下面重启项目后访问地址：<a href="127.0.0.1:8080/updateWithQueryDsl?id=6&amp;name=changeWithQueryDsl&amp;age=24&amp;address=山东济南&amp;pwd=666666" target="_blank" rel="noopener">127.0.0.1:8080/updateWithQueryDsl?id=6&amp;name=changeWithQueryDsl&amp;age=24&amp;address=山东济南&amp;pwd=666666</a>，界面输出内容如下图4所示：<br><img src="http://upload-images.jianshu.io/upload_images/4461954-3ed6067bca583a49.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图4">，我们发现这里出现了系统异常，我们来看下控制台输出的错误信息如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">javax.persistence.TransactionRequiredException: Executing an update/delete query</span><br><span class="line">    at org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:54) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]</span><br><span class="line">    at com.querydsl.jpa.impl.JPAUpdateClause.execute(JPAUpdateClause.java:77) ~[querydsl-jpa-4.1.4.jar:na]</span><br><span class="line">    at com.yuqiyu.querydsl.sample.chapter3.controller.UserController.updateWithQueryDsl(UserController.java:76) ~[classes/:na]</span><br><span class="line">.......</span><br></pre></td></tr></table></figure></p>
<p>发现如果想执行update/delete方法时必须存在一个事务才可以，那我们修改更新方法添加事务注解@Transactional,重启项目再来访问我们之前的地址，界面输出内容如下图5所示：<br><img src="http://upload-images.jianshu.io/upload_images/4461954-08ec7d76c93dac33.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图5">，界面输出了执行成功的提示，我们来看下控制台输出的SQL语句：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Hibernate: </span><br><span class="line">    update</span><br><span class="line">        t_user </span><br><span class="line">    set</span><br><span class="line">        t_name=?,</span><br><span class="line">        t_address=?,</span><br><span class="line">        t_age=?,</span><br><span class="line">        t_pwd=? </span><br><span class="line">    where</span><br><span class="line">        t_id=?</span><br></pre></td></tr></table></figure></p>
<p>控制台输出的这个SQL语句就是QueryDsl根据我们配置的更新实体、更新字段、查询条件自动生成的，是不是比较灵活？</p>
<h3 id="使用SpringDataJPA删除实体信息"><a href="#使用SpringDataJPA删除实体信息" class="headerlink" title="使用SpringDataJPA删除实体信息"></a>使用SpringDataJPA删除实体信息</h3><p>下面我们来看看SpringDataJPA删除实体信息时该怎么处理？代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 使用Jpa删除会员信息</span><br><span class="line"> * @param userBean</span><br><span class="line"> */</span><br><span class="line">@RequestMapping(value = &quot;/deleteWithJpa&quot;)</span><br><span class="line">public String deleteWithJpa(UserBean userBean)</span><br><span class="line">&#123;</span><br><span class="line">    //执行删除指定主键的值</span><br><span class="line">    userJPA.delete(userBean.getId());</span><br><span class="line">    return &quot;SUCCESS&quot;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面代码我们根据主键删除了指定的实体，下面我们重启项目后访问地址：<a href="http://127.0.0.1:8080/deleteWithJpa?id=6" target="_blank" rel="noopener">http://127.0.0.1:8080/deleteWithJpa?id=6</a>，控制台输出的SQL内容如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Hibernate: </span><br><span class="line">    delete </span><br><span class="line">    from</span><br><span class="line">        t_user </span><br><span class="line">    where</span><br><span class="line">        t_id=?</span><br></pre></td></tr></table></figure></p>
<p>输出的SQL也是按照我们指定的主键完成了删除逻辑。</p>
<h3 id="使用QueryDsl删除会员信息"><a href="#使用QueryDsl删除会员信息" class="headerlink" title="使用QueryDsl删除会员信息"></a>使用QueryDsl删除会员信息</h3><p>在编写删除方法之前我们想到了之前使用QueryDsl更新实体时需要添加事务，当然在删除的时候也是需要的所以我们编写删除方法时要注意，删除代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">    * 使用QueryDsl删除会员信息</span><br><span class="line">    * @param userBean</span><br><span class="line">    */</span><br><span class="line">   @RequestMapping(value = &quot;/deleteWithQueryDsl&quot;)</span><br><span class="line">   @Transactional</span><br><span class="line">   public String deleteWithQueryDsl(UserBean userBean)</span><br><span class="line">   &#123;</span><br><span class="line">       //querydsl查询实体</span><br><span class="line">       QUserBean _Q_user = QUserBean.userBean;</span><br><span class="line"></span><br><span class="line">       queryFactory</span><br><span class="line">               //删除对象</span><br><span class="line">               .delete(_Q_user)</span><br><span class="line">               //删除条件</span><br><span class="line">               .where(_Q_user.id.eq(userBean.getId()))</span><br><span class="line">               //执行删除</span><br><span class="line">               .execute();</span><br><span class="line">       return &quot;SUCCESS&quot;;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>QueryDsl的删除编写与更新几乎是差不多的，只是把update方法改成了delete方法，当然where条件也可以添加多个，这个需要看个人实际业务逻辑。</p>
<p>删除语句编写完成后调用execute方法后QueryDsl才去处理删除逻辑。重启项目后，访问地址：<a href="127.0.0.1:8080/deleteWithQueryDsl?id=7" target="_blank" rel="noopener">127.0.0.1:8080/deleteWithQueryDsl?id=7</a>，查看控制台输出SQL内容如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Hibernate: </span><br><span class="line">    delete </span><br><span class="line">    from</span><br><span class="line">        t_user </span><br><span class="line">    where</span><br><span class="line">        t_id=?</span><br></pre></td></tr></table></figure></p>
<p>下面我们修改下删除条件，我们根据名称以及年龄大于20岁条件执行删除，修改后的方法代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">@RequestMapping(value = &quot;/deleteWithQueryDsl&quot;)</span><br><span class="line">@Transactional</span><br><span class="line">public String deleteWithQueryDsl(UserBean userBean)</span><br><span class="line">&#123;</span><br><span class="line">    //querydsl查询实体</span><br><span class="line">    QUserBean _Q_user = QUserBean.userBean;</span><br><span class="line"></span><br><span class="line">    queryFactory</span><br><span class="line">            //删除对象</span><br><span class="line">            .delete(_Q_user)</span><br><span class="line">            //删除条件</span><br><span class="line">            .where(</span><br><span class="line">                    _Q_user.name.eq(userBean.getName())</span><br><span class="line">                    .and(_Q_user.age.gt(20))</span><br><span class="line">            )</span><br><span class="line">            //执行删除</span><br><span class="line">            .execute();</span><br><span class="line">    return &quot;SUCCESS&quot;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>重启项目后访问地址：<a href="http://127.0.0.1:8080/deleteWithQueryDsl?name=admin&amp;age=20" target="_blank" rel="noopener">http://127.0.0.1:8080/deleteWithQueryDsl?name=admin&amp;age=20</a>，控制台输出SQL如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Hibernate: </span><br><span class="line">    delete </span><br><span class="line">    from</span><br><span class="line">        t_user </span><br><span class="line">    where</span><br><span class="line">        t_name=? </span><br><span class="line">        and t_age&gt;?</span><br></pre></td></tr></table></figure></p>
<p>输出的SQL完全根据我们设置的条件来自动生成，QueryDsl内的条件可以跟原生SQL完全一样，可以完全采用SQL的思想来编写条件。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>以上内容就是本章的全部内容，本章主要讲解了QueryDsl是怎么操作单表Delete&amp;Update操作以及SpringDataJPA操作单表Delete&amp;Update。<br>本章代码已经上传到码云：<br>SpringBoot配套源码地址：<a href="https://gitee.com/hengboy/spring-boot-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-boot-chapter</a><br>SpringCloud配套源码地址：<a href="https://gitee.com/hengboy/spring-cloud-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-cloud-chapter</a><br>SpringBoot相关系列文章请访问：<a href="http://www.jianshu.com/p/9a08417e4e84" target="_blank" rel="noopener">目录：SpringBoot学习目录</a><br>QueryDSL相关系列文章请访问：<a href="http://www.jianshu.com/p/99a5ec5c3bd5" target="_blank" rel="noopener">QueryDSL通用查询框架学习目录</a><br>SpringDataJPA相关系列文章请访问：<a href="http://www.jianshu.com/p/615ed9c1fe84" target="_blank" rel="noopener">目录：SpringDataJPA学习目录</a><br>感谢阅读！<br>欢迎加入QQ技术交流群，共同进步。<br><img src="http://upload-images.jianshu.io/upload_images/4461954-f1d4cb64234b160a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="QQ技术交流群"></p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">


    <div class="bdsharebuttonbox">
    <a href="#" class="bds_more" data-cmd="more">分享到：</a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间">QQ空间</a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博">新浪微博</a>
    <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博">腾讯微博</a>
    <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网">人人网</a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信">微信</a>
</div>
<script>
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{"bdSize":16}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<style>
    .bdshare_popup_box {
        border-radius: 4px;
        border: #e1e1e1 solid 1px;
    }
    .bdshare-button-style0-16 a,
    .bdshare-button-style0-16 .bds_more {
        padding-left: 20px;
        margin: 6px 10px 6px 0;
    }
    .bdshare_dialog_list a,
    .bdshare_popup_list a,
    .bdshare_popup_bottom a {
        font-family: 'Microsoft Yahei';
    }
    .bdshare_popup_top {
        display: none;
    }
    .bdshare_popup_bottom {
        height: auto;
        padding: 5px;
    }
</style>


</div>

            
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/querydsl-chapter-4/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    第四章：使用QueryDSL与SpringDataJPA实现多表关联查询
                
            </div>
        </a>
    
    
        <a href="/querydsl-chapter-2/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">第二章：使用QueryDSL与SpringDataJPA实现单表普通条件查询</div>
        </a>
    
</nav>


    
</article>


    
    

</section>
            
			
				
<aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">最新文章</h3>
        <div class="widget">
            <ul id="recent-post" class="no-thumbnail">
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-52/" class="title">第五十二章：基于SpringBoot2使用Rest访问MongoDB数据</a></p>
                            <p class="item-date"><time datetime="2018-04-21T16:00:00.000Z" itemprop="datePublished">2018-04-22</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-51/" class="title">第五十一章：基于SpringBoot2 &amp; MongoDB完成自动化集成</a></p>
                            <p class="item-date"><time datetime="2018-04-15T16:00:00.000Z" itemprop="datePublished">2018-04-16</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-50/" class="title">第五十章：SpringBoot2.0新特性 - 岂止至今最简单redis缓存集成</a></p>
                            <p class="item-date"><time datetime="2018-04-14T16:00:00.000Z" itemprop="datePublished">2018-04-15</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-49/" class="title">第四十九章：SpringBoot2.0新特性 - 你get到WebMvcConfigurer两种配置方式了吗？</a></p>
                            <p class="item-date"><time datetime="2018-03-16T16:00:00.000Z" itemprop="datePublished">2018-03-17</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-48/" class="title">第四十八章：SpringBoot2.0新特性 - RabbitMQ信任package设置</a></p>
                            <p class="item-date"><time datetime="2018-03-12T16:00:00.000Z" itemprop="datePublished">2018-03-13</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">分类</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/QueryDSL-核心技术/">QueryDSL 核心技术</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a><span class="category-list-count">36</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">归档</h3>
        <div class="widget">
            <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/04/">四月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">三月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/01/">一月 2018</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/12/">十二月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/11/">十一月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/10/">十月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/09/">九月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/08/">八月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/07/">七月 2017</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/06/">六月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/05/">五月 2017</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/04/">四月 2017</a><span class="archive-list-count">5</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签</h3>
        <div class="widget">
            <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/QueryDSL/">QueryDSL</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/SpringBoot/">SpringBoot</a><span class="tag-list-count">43</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签云</h3>
        <div class="widget tagcloud">
            <a href="/tags/QueryDSL/" style="font-size: 10px;">QueryDSL</a> <a href="/tags/SpringBoot/" style="font-size: 20px;">SpringBoot</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title">链接</h3>
        <div class="widget">
            <ul>
                
                    <li>
     				<a href="http://hexo.io" target="_blank">Hexo</a>
					</li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>

				
        </div>
        <!--引入不蒜子-->
<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            <span  id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
            &copy; 2017 - 2018 恒宇少年 - 版权所有<br>
        </div>
    </div>
</footer>

        


    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>